<template>
  <el-dialog
    :append-to-body="true"
    :visible.sync="dialog"
    :title="isAdd ? '新增字典' : '编辑字典'"
    width="500px"
  >
    <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
      <el-form-item label="字典名称" prop="name">
        <el-input v-model="form.name" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="form.value" style="width: 370px;"/>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { dictionary_add, dictionary_update } from '@/api/system';
export default {
  props: {
    isAdd: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      loading: false,
      dialog: false,
      form: {
        id: null,
        name: '',
        lv: 2,
        value: '',
        supplement: '',
        parentId: 1
      },
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      }
    };
  },
  methods: {
    cancel() {
      this.resetForm();
    },
    doSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.isAdd) {
            this.doAdd();
          } else this.doEdit();
        }
      });
    },
    async doAdd() {
      try {
        await dictionary_add(this.form);
        this.resetForm();
        this.$message({
          message: '添加成功',
          type: 'success'
        });
        this.loading = false;
        this.$parent.getDictionries();
      } catch (error) {
        console.error(error);
        this.loading = false;
      }
    },
    async doEdit() {
      try {
        await dictionary_update(this.form);
        this.resetForm();
        this.$message({
          message: '修改成功',
          type: 'success'
        });
        this.loading = false;
        this.$parent.getDictionries();
      } catch (error) {
        console.error(error);
        this.loading = false;
      }
    },
    resetForm() {
      this.dialog = false;
      this.$refs['form'].resetFields();
      this.form = {
        id: null,
        name: '',
        lv: 2,
        value: '',
        supplement: '',
        parentId: 1
      };
    }
  }
};
</script>
